const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
const { returnColumnHotData,returnColumnMessage } = require('../utils/prismaData');
const upload = require('../multer/multer');
const { parseToken } = require('../utils/token');


/* GET users listing. */
// 获取推荐专栏数据
router.get('/hot',async (req, res) => {
  const columnsData = await prisma.column.findMany({
    select:{
      id: true,
      name: true,
      mainPath: true,
      createUser: {
        select: {
          id: true,
          name: true
        }
      } ,
      article: {
        select: {
          articleId: true
        }
      },
      follow: {
        select:{
          userId: true
        }
      }
    }
  })
  // 包装数据

  res.status(200).send(returnColumnHotData(columnsData));
});

// 获取指定id专栏数据
router.get('/column', upload.none(), async (req, res) => {
  const token = req.headers.authorization.split(' ')[1]
  const tokenData = await parseToken(token)
  if (!tokenData) return res.status(401).send({ msg: '登录过期' })
  const { id } = tokenData
  const {columnId} = req.query
  const columnData = await prisma.column.findUnique({
    where: {
      id: columnId
    },
    select: {
      id: true,
      name: true,
      mainPath: true,
      createAt: true,
      createUser: {
        select: {
          id: true,
          name: true,
          img: true
        }
      },
      follow: true
    }
  })
  if (columnData === null) return res.status(404).send('无可用数据')
  res.status(200).send(returnColumnMessage(columnData, id));
})

// 收藏一个专栏
router.post('/like', upload.none(), async (req, res) => {
  const token = req.headers.authorization.split(' ')[1]
  const tokenData = await parseToken(token)
  if (!tokenData) return res.status(401).send({ msg: '登录过期' })
  const { id } = tokenData
  const { columnId, userId } = req.body
  if (id !== userId) return res.status(403).send({msg: '错误的用户信息'})
  const followArticle = await prisma.followColumn.upsert({
      where: {
        columnId_userId:{
              columnId: columnId,
              userId: id
          }
      },
      update: {},
      create: {
          columnId: columnId,
          userId: id
      }
  })
  if (followArticle === null) res.status(401).send({msg: '数据库操作错误'})
  res.status(200).send({msg: '已添加到收藏'})
})





  

module.exports = router;
